package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;

import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    AddressBookMapper addressBookMapper;

    /**
     * 新增地址
     * @param addressBook
     * @return
     */
    public void add(AddressBook addressBook) {
//        获取用户的id
        Long currentId = BaseContext.getCurrentId();
//        根据用户id插入的地址
        addressBook.setUserId(currentId);
        addressBook.setIsDefault(0);
        addressBookMapper.add(addressBook);
    }

    /**
     * 查询用户所有的地址
     * @return
     */
    public List<AddressBook> selectAll() {
//        获取当前用户的id
        Long currentId = BaseContext.getCurrentId();
//        根据id去数据库查
        List<AddressBook> a = addressBookMapper.selectAll(currentId);
        return a;
    }

    /**
     * 设置默认地址
     * @param addressBook
     * @return
     */
    public void defaultAddress(AddressBook addressBook) {
        //1、将当前用户的所有地址修改为非默认地址 update address_book set is_default = ? where user_id = ?
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateIsDefaultByUserId(addressBook);

        //2、将当前地址改为默认地址 update address_book set is_default = ? where id = ?
        addressBook.setIsDefault(1);
        addressBookMapper.update(addressBook);
    }

    /**
     * 查询默认地址
     */
    public List<AddressBook> selectDeAddress(AddressBook addressBook) {
        return addressBookMapper.selectDeAddress(addressBook);

    }


    /**
     * 根据id删除地址
     *
     * @param id
     */
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }



    /**
     * 根据id修改地址
     *
     * @param addressBook
     * @return
     */
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }


    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    public AddressBook selectById(Integer id) {
        AddressBook addressBook = addressBookMapper.selectById(id);
        return addressBook;
    }
}
